package com.qing.microservices.shirostudy.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.qing.microservices.shirostudy.entity.User;
import com.qing.microservices.shirostudy.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author guoqf
 */
public class UsernameRealm extends AuthorizingRealm {


    private final IUserService userService;

    public UsernameRealm(@Autowired IUserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 登录名
        String principal = (String) authenticationToken.getPrincipal();
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, principal));
        // 用户存在
        if (user != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPasswd(), this.getName());
            return info;
        }

        return null;
    }
}
